<?php

namespace App\Models\Schedule;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ScheduleUserChangeLogModel extends BaseModel
{
    use KfUid;

    protected $table = "schedule_user_change_logs";

    protected $fillable = [
        'shopId',
        'userId',
        'date',
        'ruleId',
        'type',
        'beforeData',
        'afterData',
    ];

    const TYPE_SINGLE = 1; // 修改个人排班
    const TYPE_RULE   = 2; // 修改班次管理

    public function add(int $shopId, int $userId, int $date, int $ruleId, int $type)
    {
        if ($this->compareBeforeAfterData()) {
            return null;
        }

        return self::query()->create([
            'shopId'     => $shopId,
            'userId'     => $userId,
            'date'       => $date,
            'ruleId'     => $ruleId,
            'type'       => $type,
            'beforeData' => json_encode($this->beforeData),
            'afterData'  => json_encode($this->afterData),
        ]);
    }

    public function setBeforeData(array $beforeData): self
    {
        $this->beforeData = $beforeData;

        return $this;
    }

    public function setAfterData(array $afterData): self
    {
        $this->afterData = $afterData;

        return $this;
    }

    /**
     * 校验before/after data的值是否相同
     * @return bool
     */
    public function compareBeforeAfterData(): bool
    {
        $beforeData = array_values($this->beforeData);
        $afterData = array_values($this->afterData);

        unset($beforeData['createdAt']);
        unset($beforeData['updatedAt']);
        unset($afterData['updatedAt']);
        unset($afterData['updatedAt']);

        if ($beforeData == $afterData) {
            return true;
        } else {

            return false;
        }
    }

    public function scheduleRemindSwitchRel(): HasMany
    {
        return $this->hasMany(ScheduleRemindSwitchModel::class, "userId", "userId");
    }
}
